package com.adcc.sgs.gcs;

import com.adcc.sgs.gcs.db.DBAccess;
import com.adcc.sgs.gcs.proxy.AdapterProxy;
import com.google.common.base.Optional;
import com.smartUtility.common.log.Log;
import com.smartUtility.mq.MQBundle;
import com.smartUtility.mq.MQFactory;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.eclipse.jetty.io.Connection;

/**
 * Created by nk on 2016/8/15.
 */
public class App extends Application<AppConfiguration> {
    private MQBundle<AppConfiguration> outMQBundle = new MQBundle<AppConfiguration>() {
        @Override
        public MQFactory getMQFactory(AppConfiguration configuration) {
            return configuration.getMqSendFactory();
        }
    };
    private MQBundle<AppConfiguration> inMQBundle = new MQBundle<AppConfiguration>() {
        @Override
        public MQFactory getMQFactory(AppConfiguration configuration) {
            return configuration.getMqRecvFactory();
        }
    };

    @Override
    public void initialize(Bootstrap<AppConfiguration> bootstrap) {
        try {
            super.initialize(bootstrap);

            // 注册MQBundle
            bootstrap.addBundle(inMQBundle);
            bootstrap.addBundle(outMQBundle);

        } catch (Exception ex) {
            Log.error(getClass().getName(), "initialize error:" + ex);
        }
    }

    @Override
    public void run(AppConfiguration appConfiguration, Environment environment) throws Exception {
        try {
            // 初始化DB
            DBAccess dbAccess = new DBAccess();
            dbAccess.build(environment, appConfiguration.getDbResource());
            AdapterProxy.getInstance().setDbAccess(Optional.of(dbAccess));
            // 设置PROXY
            AdapterProxy.getInstance().setActivemqRecvClient(Optional.of(inMQBundle.getClient()));
            AdapterProxy.getInstance().setActivemqSendClient(Optional.of(outMQBundle.getClient()));
            AdapterProxy.getInstance().build(environment);

        } catch (Exception ex) {
            Log.error(getClass().getName(), "run error:" + ex);
        }
    }

    public static void main(String[] args) throws Exception {
        String[] params = (args == null || args.length < 2) ? new String[]{"server", "./SGS/gcs/conf/conf.yml"} : args;
        App app = new App();
        app.run(params);
    }
}
